const router = require('koa-router')()
const Short = require('../db/model/short.js')
const strList = require('../config/string.js')

// router.get('/', async (ctx, next) => {
//     await ctx.render('index', {
//         title: 'Hello Koa 2!'
//     })
// })

router.get('/:code', async (ctx, next) => {
    ctx.body = ctx.params.code
    let result = await Short.find({code: ctx.params.code})
    if(result.length) {
        ctx.redirect(result[0].link)
    }
    else {
        ctx.body = '短链接已失效！'
    }
})

router.post('/add', async (ctx, next) => {
    let link = ctx.request.body.url
    let result = await Short.find({ link })
    if(result[0]) {
        ctx.body = {
            code: 200,
            result: result[0]
        }
    }
    else {
        if(link) {
            let code = await checkCode()
            let shortUrl = new Short({ code, link})
            let result = await shortUrl.save()
            ctx.body = {
                code: 200,
                result
            }
        }
        else {
            ctx.code = 500
            ctx.body = 'url为必填'
        }
    }
})

router.get('/string', async (ctx, next) => {
    ctx.body = 'koa2 string'
})

router.get('/json', async (ctx, next) => {
    ctx.body = {
        title: 'koa2 json'
    }
})

function createCode() {
    let str = ''
    for(let i = 0; i < 5; i++) {
        str += strList[Math.floor(strList.length * Math.random())]
    }
    return str
}

async function checkCode() {
    let str = createCode()
    let result = await Short.find({code: str})
    if(result.length) {
        str = checkCode()
    }
    else {
        return str
    }
}

module.exports = router